/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package university.general;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "university_general")
@RequestScoped
public class Main extends Beans {
    //Variables de importación General

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    //Variables de importación otros modulos
    //Variables del modulo
    private Find universityFind = new Find();
    private List<Beans> universityList = new ArrayList<>();
    //Variables locales
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
        load();
    }

    private void load() {
        try {

            if (logged.getMasterId() == 0) {
                return;
            }

            map.clear();
            map.put("id = " + logged.getMasterId(), " ");

            universityList.clear();
            universityList = universityFind.byMap(map);

            setId(universityList.get(0).getId());
            setNombre(universityList.get(0).getNombre());
            setFundada(universityList.get(0).getFundada());
            setDetalle(universityList.get(0).getDetalle());

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {
            //Verifica si el registro existe, de lo contrario lo inserta
            map.clear();
            map.put("lower(nombre) = '" + getNombre().toLowerCase() + "'", " ");

            if (universityFind.byExist(map)) {
                throw new Exc("m5");
            }
            sql = "INSERT INTO public.universidad_general (nombre,fundada, detalle) "
                    + " VALUES ('" + getNombre() + "'," + getFundada() + ",'" + getDetalle() + "')";

            //Inserta la información del registro
            persistencia.executeUpdate(sql);

            //Localiza el id del registro recien insertado, con la llave única
            universityList = universityFind.byMap(map);

            //Asigna el id del registro insertado a la variable global
            logged.setMasterId(universityList.get(0).getId());
            logged.setMasterName(getNombre());

            throw new Exc("m1");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public int insert(String nombre, Integer fundada, String detalle) throws Exc, SQLException, Exception {
        setNombre(nombre);
        setFundada(fundada);
        setDetalle(detalle);
        insert();
        //localiza el registro devuelve el id generado
        universityList = universityFind.byMap(map);
        return universityList.get(0).getId();
    }

    public void update() {
        try {
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }
            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m6");
            }

            //Verifica si el registro existe, de lo contrario lo inserta
            map.clear();
            map.put("id <> " + logged.getMasterId(), " AND ");
            map.put("lower(nombre) = '" + getNombre().toLowerCase() + "'", " ");

            if (universityFind.byExist(map)) {
                throw new Exc("m5");
            }
            sql = "UPDATE public.universidad_general SET "
                    + "nombre= '" + getNombre() + "', "
                    + "fundada= " + getFundada() + ", "
                    + "detalle='" + getDetalle() + "' "
                    + "WHERE id =" + logged.getMasterId();

            logged.setMasterName(getNombre());

            //Actualiza la información del registro
            persistencia.executeUpdate(sql);
            throw new Exc("m2");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void delete() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id_persona
            deleteById(logged.getMasterId());
            clear();

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {
        //Verifica si el usuario ya existe para otra persona
        sql = "DELETE FROM public.universidad_general "
                + "WHERE id = " + id;
        persistencia.executeUpdate(sql);
    }

    public void clear() {
        logged.clearRecord();
        clearBeans();
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }
}
